package com.yitongmao.bottompop;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.widget.EditText;

import com.yitongmao.common.reminder.ReaderApplication;

import java.lang.reflect.Field;


public class UIUtils {

    public static final String intentKey = "className";
    public static final String intentData = "data";
    public static String intentCode = "code";

    /**
     * dip转换px
     */
    public static int dip2px(int dip) {
        final float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f);
    }

    /**
     * pxz转换dip
     */

    public static int px2dip(int px) {
        final float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    /**
     * 根据资源id 获取字符串数组
     *
     * @param id
     * @return
     */
    public static String[] getStringArray(int id) {
        return getResources().getStringArray(id);
    }

    /**
     * 获取Resources对象
     *
     * @return
     */
    public static Resources getResources() {
        return getContext().getResources();
    }

    /**
     * 获取上下文对象
     *
     * @return
     */
    public static Context getContext() {
        return ReaderApplication.getInstace();
    }

    /**
     * xml --->View对象
     *
     * @param id
     * @return
     */
    public static View inflate(int id) {
        return View.inflate(UIUtils.getContext(), id, null);
    }

    /**
     * 获取屏幕密度
     */
    public static int getDenisty(Activity activity) {
        //        获取屏幕密度
        DisplayMetrics metric = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
        return metric.densityDpi;
    }

    /**
     * 获取dimens
     *
     * @param id
     * @return
     */
    public static int getDimens(int id) {
        return getResources().getDimensionPixelSize(id);
    }









    /**
     * id --- >string
     *
     * @param id
     * @return
     */
    public static String getString(int id) {
        return getResources().getString(id);
    }

    /**
     * id_---->Drawable
     *
     * @param id
     * @return
     */
    public static Drawable getDrawable(int id) {
        return getResources().getDrawable(id);
    }

    /**
     * 弹出键盘
     */
    public static void showKeyboard(View v) {
        ((InputMethodManager) getContext().getSystemService(getContext().INPUT_METHOD_SERVICE))
                .showSoftInput(v, 0);
    }

    /**
     * 切换键盘
     */
    public static void openKeyboard() {
        InputMethodManager imm = (InputMethodManager) getContext()

                .getSystemService(Context.INPUT_METHOD_SERVICE);

        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

    }

    /**
     * fragment中隐藏键盘,键盘的显示和隐藏于activity有直接关系，需要使用activity
     */
    public static void hideKeyboard(Fragment fragment) {
        ((InputMethodManager) fragment.getActivity().getSystemService(fragment.getActivity().INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow((fragment.getActivity().getCurrentFocus().getWindowToken()),
                        InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * fragment中隐藏键盘,键盘的显示和隐藏于activity有直接关系，需要使用activity
     */
    public static void hideKeyboard(Activity activity) {
        View currentFocus = activity.getCurrentFocus();
        if (currentFocus == null)
            return;
        IBinder windowToken = currentFocus.getWindowToken();
        if (windowToken == null)
            return;
        ((InputMethodManager) activity.getSystemService(activity.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(windowToken,
                        InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 限制小数点后个数
     *
     * @param num 小数点后位个数
     */
    public static void setDeciNum(final EditText editText, final int num) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > num) {
                        s = s.toString().subSequence(0, s.toString().indexOf(".") + num + 1);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }
                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }




    /**
     * 隐藏对话框
     *
     * @param dialog
     */
    public static void dismissDialog(ProgressDialog dialog) {
        if (dialog != null && dialog.isShowing())
            dialog.dismiss();
    }

    /**
     * 释放因为InputMethodManager造成的内存泄漏
     *
     * @param destContext
     */
    public static void fixInputMethodManagerLeak(Context destContext) {
        if (destContext == null) {
            return;
        }

        InputMethodManager imm = (InputMethodManager) destContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }

        String[] arr = new String[]{"mCurRootView", "mServedView", "mNextServedView"};
        Field f;
        Object obj_get;
        for (int i = 0; i < arr.length; i++) {
            String param = arr[i];
            try {
                f = imm.getClass().getDeclaredField(param);
                if (f.isAccessible() == false) {
                    f.setAccessible(true);
                }
                obj_get = f.get(imm);
                if (obj_get != null && obj_get instanceof View) {
                    View v_get = (View) obj_get;
                    if (v_get.getContext() == destContext) { // 被InputMethodManager持有引用的context是想要目标销毁的
                        f.set(imm, null); // 置空，破坏掉path to gc节点
                    }
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }

    /**
     * 获取key3
     *
     * @param key3
     * @return
     */
    public static String getkey(int key3) {
        return getString(key3);
    }

    /**
     * 获取Cookie值
     *
     * @param url
     * @return
     */
    public static String getCookie(String url) {
        CookieManager instance = CookieManager.getInstance();
        return instance.getCookie(url);
    }
}
